package 树;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * <p>
 * https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
 * 给定一个 N 叉树，返回其节点值的前序遍历。
 * </p>
 *
 * @author AJun
 * @since 2020/8/23
 */
public class _589_N叉树的前序遍历 {

    public List<Integer> preorder(Node root) {
        Stack<Node> stack = new Stack<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }

        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            output.add(node.val);
            Collections.reverse(node.children);
            for (Node item : node.children) {
                if (item != null) {
                    stack.push(item);
                }
            }
        }
        return output;
    }

}
